package wechat.base.snd

import wechat.base.snd.encoding.JsonPut
import wechat.base.snd.util.ExecPost
import org.json.JSONObject
import org.apache.log4j.Logger;
import java.io.File
import wechat.base.snd.util.ExecGet
import org.eclipse.xtend.lib.annotations.Accessors

class QRCodeManager{
	static String WECHAT_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
	static Logger logger = Logger::getLogger("QRCodeManager")
	
	QRCode qrcode;
	
	@Accessors WCServiceApp app;
	new (WCServiceApp a){
		this.app = a
	}
	def getQRCodeUrl(){
		WECHAT_QRCODE_URL + this.app.token;
	}
	def QRCodeManager genPermTicket(QRCode _qrcode){
		qrcode = _qrcode;
		logger.info(QRCodeUrl)
		logger.info(qrcode.toPermJsonRequst.toString)
		ExecPost::excuteJsonPost(QRCodeUrl, qrcode.toPermJsonRequst.toString)=>[
			new JSONObject(it)=>[
				logger.info(it.toString)
				qrcode.ticket =  it.getString('ticket')	
			]
		]	
		this
	}
	def QRCodeManager genTempTicket(QRCode _qrcode){
		qrcode = _qrcode;
		logger.info(QRCodeUrl)
		logger.info(qrcode.toTempJsonRequst.toString)
		ExecPost::excuteJsonPost(QRCodeUrl, qrcode.toTempJsonRequst.toString)=>[
			new JSONObject(it)=>[
				logger.info(it.toString)
				qrcode.ticket =  it.getString('ticket')	
			]
		]
		this
	}
	def File getTicket(String filename_prefix){
		ExecGet::excuteGetImg("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+qrcode.ticket, filename_prefix+".jpg")	
	}
}
class QRCode {
	@Accessors String action_name
	@Accessors String scene_str
	@Accessors String scene_id
	@Accessors String ticket
	@Accessors String expire_seconds
	@Accessors String url
	new (String scene_id_str){
//		this.scene_id =  scene_id_str
		this.scene_str = scene_id_str
	}
	def JSONObject toPermJsonRequst(){
		this.action_name = 'QR_LIMIT_STR_SCENE'
		new JsonPut()=>[
			putObj('action_info',new JsonPut()=>[
				putObj('scene', new JsonPut()=>[
					putObj('scene_str', scene_str)
				])
			])
			putObj('action_name',action_name)
		]
	}
	def JSONObject toTempJsonRequst(){
		this.action_name = 'QR_SCENE'
		new JsonPut()=>[
			putObj('expire_seconds',604800)
			putObj('action_name',action_name)
			putObj('action_info',new JsonPut()=>[
				putObj('scene', new JsonPut()=>[
					putObj('scene_id', scene_id)
				])
			])
		]
	}	
}